﻿using Newtonsoft.Json;
using System;
using System.Globalization;
using System.Runtime.Serialization;

namespace DbJobsApi.Extensions
{
    /// <summary>
    /// 正则表达式String的Json格式过滤器
    /// </summary>
    public class RegexStringConverter : JsonConverter
    {
        private readonly string filter;
        /// <summary>
        /// 正则表达式String的Json格式过滤器
        /// </summary>
        /// <param name="filter">例如yyyyMMdd HH:mm:ss</param>
        public RegexStringConverter(string filter)
        {
            this.filter = filter;
        }

        public override bool CanConvert(Type objectType)
        {
            return true;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.Value != null && !string.IsNullOrEmpty(reader.Value.ToString()))
            {
                var result = reader.Value.ToString();
                var reg = new System.Text.RegularExpressions.Regex(filter);
                var flag = reg.IsMatch(result);
                if (flag)
                    return result;
                else
                    throw new JsonReaderException($"该参数包含非法字符 {reader.Path}", reader.Path, 1, 1, null);
            }
            return null;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var val = (string)value;
            if (val != null)
            {
                writer.WriteValue(val);
            }
        }
    }
}
